/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: AbstractFuncation.java   2020-10-14 15-56-00
 * Author: Evan
 */
package cn.datacare.orm.engine.function;

import cn.datacare.orm.manager.impl.SQLManager;
import cn.datacare.orm.source.SQLResult;
import org.beetl.core.Context;

import java.util.Map;

import static cn.datacare.orm.constant.Constants.PARAM_ID;
import static cn.datacare.orm.util.Separator.DOT;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-14 15-56-00
 * @since V1.0
 */
public abstract class AbstractFunction {

    /**
     * 参数大小
     */
    protected static final int PARAMS_SIZE = 2;

    /**
     * 文件
     *
     * @param context
     * @param params
     * @return SQLResult
     */
    public SQLResult getSqlResult(SQLManager sqlManager, Context context, Object[] params) {

        Map<String, Object> inputParams = context.globalVar;
        if (params.length == PARAMS_SIZE) {
            Map map = (Map) params[1];
            map.putAll(inputParams);
            inputParams = map;
        }
        String file = this.getParentId(context);
        String id = (String) params[0];
        return sqlManager.getSQLResult(file + DOT + id, inputParams, context);
    }


    /***
     * 获取文件file
     * @param ctx  Context
     * @return file
     */
    protected String getParentId(Context ctx) {
        String id = (String) ctx.getGlobal(PARAM_ID);
        int index = id.lastIndexOf(DOT);
        String file = id.substring(0, index);
        return file;
    }
}
